package com.hyphenate.easeui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.adapter.EaseMessageAdapter;
import com.hyphenate.easeui.model.styles.EaseMessageListItemStyle;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class EaseChatMessageList extends RelativeLayout {

    protected static final String TAG = "EaseChatMessageList";
    protected ListView listView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected Context context;
    protected EMConversation conversation;
    protected int chatType;
    protected String toChatUsername;
    protected EaseMessageAdapter messageAdapter;
    protected EaseMessageListItemStyle itemStyle;
    private HashMap<String, EMMessage> sendingMessages;

    public EaseChatMessageList(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }


    public EaseChatMessageList(Context context, AttributeSet attrs) {
        super(context, attrs);
        parseStyle(context, attrs);
        init(context);
    }

    public EaseChatMessageList(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.ease_chat_message_list, this);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.chat_swipe_layout);
        listView = (ListView) findViewById(R.id.list);
        //
        View view = LayoutInflater.from(context).inflate(R.layout.ease_case_list_shit_footer, null);
        listView.addFooterView(view);
    }

    /**
     * init widget
     *
     * @param toChatUsername
     * @param chatType
     * @param customChatRowProvider
     */
    public void init(String toChatUsername, int chatType, EaseCustomChatRowProvider customChatRowProvider) {
        this.chatType = chatType;
        this.toChatUsername = toChatUsername;

        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
//        conversation.appendMessage();
        messageAdapter = new EaseMessageAdapter(context, toChatUsername, chatType, listView);
        messageAdapter.setItemStyle(itemStyle);
        messageAdapter.setCustomChatRowProvider(customChatRowProvider);
        // set message adapter
        listView.setAdapter(messageAdapter);

//        refreshSelectLast();
    }

    protected void parseStyle(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EaseChatMessageList);
        EaseMessageListItemStyle.Builder builder = new EaseMessageListItemStyle.Builder();
        builder.showAvatar(ta.getBoolean(R.styleable.EaseChatMessageList_msgListShowUserAvatar, true))
                .showUserNick(ta.getBoolean(R.styleable.EaseChatMessageList_msgListShowUserNick, false))
                .myBubbleBg(ta.getDrawable(R.styleable.EaseChatMessageList_msgListMyBubbleBackground))
                .otherBuddleBg(ta.getDrawable(R.styleable.EaseChatMessageList_msgListMyBubbleBackground));

        itemStyle = builder.build();
        ta.recycle();
    }


    /**
     * refresh
     */
    public void refresh() {
        if (messageAdapter != null) {
            messageAdapter.refresh();
        }
    }

    /**
     * refresh and jump to the last
     */
    public void refreshSelectLast() {
        if (messageAdapter != null) {
            messageAdapter.refreshSelectLast();
        }
    }

    /**
     * refresh and jump to the position
     *
     * @param position
     */
    public void refreshSeekTo(int position) {
        if (messageAdapter != null) {
            messageAdapter.refreshSeekTo(position);
        }
    }

    public ListView getListView() {
        return listView;
    }

    public SwipeRefreshLayout getSwipeRefreshLayout() {
        return swipeRefreshLayout;
    }

    public EMMessage getItem(int position) {
        return messageAdapter.getItem(position);
    }

    public void setShowUserNick(boolean showUserNick) {
        itemStyle.setShowUserNick(showUserNick);
    }

    public boolean isShowUserNick() {
        return itemStyle.isShowUserNick();
    }


    public interface MessageListItemClickListener {
        void onResendClick(EMMessage message);

        /**
         * there is default handling when bubble is clicked, if you want handle it, return true
         * another way is you implement in onBubbleClick() of chat row
         *
         * @param message
         * @return
         */
        boolean onBubbleClick(EMMessage message);

        void onBubbleLongClick(EMMessage message);

        void onUserAvatarClick(String username);

        void onUserAvatarLongClick(String username);

        void onLickClick(EMMessage message);
    }

    /**
     * set click listener
     *
     * @param listener
     */
    public void setItemClickListener(MessageListItemClickListener listener) {
        if (messageAdapter != null) {
            messageAdapter.setItemClickListener(listener);
        }
    }

    /**
     * set chat row provider
     *
     * @param rowProvider
     */
    public void setCustomChatRowProvider(EaseCustomChatRowProvider rowProvider) {
        if (messageAdapter != null) {
            messageAdapter.setCustomChatRowProvider(rowProvider);
        }
    }

    public EaseMessageAdapter getMessageAdapter() {
        return messageAdapter;
    }

    //加载更多
    public void AddMessage(ArrayList<EMMessage> messages) {
        if (messages != null && messages.size() > 0) {
            messageAdapter.addMessage(messages);
        }
    }

    //新消息
    public void AddNewMessage(ArrayList<EMMessage> messages) {
        if (messages != null && messages.size() > 0) {
            if (haseSendingMessage()) {
                removeSendingMessage(messages);
            } else {
                messageAdapter.addNewMessage(messages);
            }
        }
    }

    public void removeSendingMessage(EMMessage message) {
        if (message != null) {
            ArrayList<EMMessage> messages = messageAdapter.getMessages(); //获取到消息
            if (messages != null) {
                ArrayList<EMMessage> currentMessages = (ArrayList) messages.clone();
                try {
                    String messageId = message.getStringAttribute("identifier");
                    for (int j = currentMessages.size() - 1; j >= 0; j--) {
                        EMMessage msg = currentMessages.get(j);
                        String shitid = msg.getStringAttribute("identifier");
                        if (shitid != null && shitid.equals(messageId)) {
                            currentMessages.remove(j);
                            removeSendMessageCache(messageId);
                            break;
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                messageAdapter.updateMessages(currentMessages);
            }
        }
    }

    private boolean haseSendingMessage() {
        return sendingMessages != null && sendingMessages.size() > 0;
    }

    //同步
    private synchronized void removeSendingMessage(ArrayList<EMMessage> newmessages) {
        ArrayList<EMMessage> messages = messageAdapter.getMessages(); //获取到消息
        if (messages != null) {
            ArrayList<EMMessage> currentMessages = (ArrayList) messages.clone();
            for (int i = 0; i < newmessages.size(); i++) {
                EMMessage newMessage = newmessages.get(i);
                try {
                    String messageId = newMessage.getStringAttribute("identifier");
                    for (int j = currentMessages.size() - 1; j >= 0; j--) {
                        EMMessage message = currentMessages.get(j);
                        String shitid = message.getStringAttribute("identifier");
                        if (shitid != null && shitid.equals(messageId)) {
                            currentMessages.remove(j);
                            removeSendMessageCache(messageId);
                            break;
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
            currentMessages.addAll(newmessages);
            messageAdapter.updateMessages(currentMessages);
        }
    }

    private void addSendMessageCache(EMMessage message) {
        if (sendingMessages == null) {
            sendingMessages = new HashMap<>();
        }
        try {
            String messageId = message.getStringAttribute("identifier");
            sendingMessages.put(messageId, message);
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }

    private void removeSendMessageCache(String key) {
        if (sendingMessages != null) {
            sendingMessages.remove(key);
        }
    }

    public void addSendMessage(EMMessage message) {
        if (message != null) {
            messageAdapter.addSendMessage(message);
            addSendMessageCache(message);
        }
    }

    public void setMessageFailed(String identifier) {
        if (identifier != null) {
            ArrayList<EMMessage> messages = messageAdapter.getMessages(); //获取到消息
            if (messages != null) {
                ArrayList<EMMessage> currentMessages = (ArrayList) messages.clone();
                try {
                    for (int j = currentMessages.size() - 1; j >= 0; j--) {
                        EMMessage msg = currentMessages.get(j);
                        String shitid = msg.getStringAttribute("identifier");
                        if (shitid != null && shitid.equals(identifier)) {
                            msg.setStatus(EMMessage.Status.FAIL);
                            break;
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                messageAdapter.updateMessages(currentMessages);
            }
        }
    }

    public void setMessageFailed(EMMessage message) {
        if (message != null) {
            try {
                String identifier = message.getStringAttribute("identifier");
                setMessageFailed(identifier);
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        }
    }

    public void AddNewMessage(EMMessage message) {
        if (message != null) {
//            messageAdapter.addNewMessage(message);
        }
    }

    public void updateLikeMessageStatus(ArrayList<EMMessage> likeMessages) {
        ArrayList<EMMessage> messages = messageAdapter.getMessages(); //获取到消息
        if (messages != null) {
            for (int i = 0; i < likeMessages.size(); i++) {
                EMMessage likeMessage = likeMessages.get(i);
                try {
                    String likemessageId = likeMessage.getStringAttribute("message_id","");
                    for (int j = 0; j < messages.size(); j++) {
                        EMMessage message = messages.get(j);
                        //
                        String messageFrom = message.getStringAttribute("message_from","");
                        String messageId;
                        if ("history".equals(messageFrom)){ //历史消息
                            messageId = message.getMsgId();
                        } else  { //实时聊天消息
                            messageId =  message.getStringAttribute("message_id","");
                        }

                        if (likemessageId.equals(messageId)) {
                            String type = likeMessage.getStringAttribute("type","");
                            int likeCnt = message.getIntAttribute("like_cnt",0);
                            if ("like".equals(type)) {
                                likeCnt++;
                            } else if ("unlike".equals(type)) {
                                likeCnt--;
                            }
                            message.setAttribute("like_cnt", likeCnt);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            messageAdapter.notifyUpdateView();//
            //
        }
    }

}
